package gen.tools.squadHost;

import gen.tools.Widgets;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class MSH extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    public MSH() {
        super();
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request,response);
	}

	/* (non-Javadoc)
	 * @see javax.servlet.http.HttpServlet#doPost(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		final Widgets wid = new Widgets();
		request.setCharacterEncoding( wid.UIcodeSet );
		response.setContentType("application/text");
		response.setCharacterEncoding( wid.UIcodeSet );
		
		final String ip = request.getParameter("ip").replace("&nbsp;", "");
		final int port = wid.getParNumberFromRequest( request.getParameter("port") );
		final String empId = request.getParameter("empId");
		final String squadId = request.getParameter("squadId");
		final String oper = request.getParameter("oper");
		final String subsysId = request.getParameter("subsysId");
		final String envId = request.getParameter("envId");
		Connection conn = null;
		PreparedStatement ps = null;
		String res = "NOTOK";
		try {
			conn = wid.getConn();
			
			if ("add".equalsIgnoreCase(oper)) {
				final String sql = "INSERT INTO mpsquadhosts (subsysid,envid,squadid,ip,port,creator,createdDateTime) VALUES(?,?,?,?,?,?,?)";
				ps = conn.prepareStatement(sql);
				ps.setString(1, subsysId);
				ps.setString(2, envId);
				ps.setString(3, squadId);
				ps.setString(4, ip);
				ps.setInt(5, port);
				ps.setString(6, empId);
				ps.setTimestamp(7, wid.cDT());
				ps.execute();
			} else {
				final String sql = "DELETE FROM mpsquadhosts WHERE subsysid=? AND envid=? AND squadid=? AND ip=? AND port=?";
				ps = conn.prepareStatement(sql);
				ps.setString(1, subsysId);
				ps.setString(2, envId);
				ps.setString(3, squadId);
				ps.setString(4, ip);
				ps.setInt(5, port);
				ps.execute();
			}
			res = "OK";
			
		} catch(Exception e) {
			wid.errLog(e);
		} finally {
			try {
				if ( ps !=null ) { ps.close(); }
				if ( conn !=null ) { conn.close(); }
			} catch (Exception e) { e.printStackTrace(); }
		}
		
		response.getWriter().write(res);
	}

}
